package cn.rubintry.bug.hunting.fragment

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewbinding.ViewBinding
import cn.rubintry.bug.common.base.BaseFragment
import cn.rubintry.bug.hunting.R
import cn.rubintry.bug.hunting.activity.ArticleDetailActivity
import cn.rubintry.bug.hunting.adapter.ArticleListAdapter
import cn.rubintry.bug.hunting.common.event.NetWorkEvent
import cn.rubintry.bug.hunting.databinding.FragmentTagArticleBinding
import cn.rubintry.bug.hunting.decoration.VerticalSpaceItemDecoration
import cn.rubintry.bug.hunting.common.http.viewmodel.DiscoverViewModel
import cn.rubintry.bug.hunting.pojo.ArticleModel
import cn.rubintry.bug.hunting.pojo.ArticleTagTable
import cn.rubintry.bug.hunting.room.DbManager
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.NetworkUtils.OnNetworkStatusChangedListener
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class TagArticleFragment : BaseFragment<FragmentTagArticleBinding>() {

    /**
     * 标签id
     */
    private var tagId: String = ""
    private val discoverViewModel : DiscoverViewModel by viewModels<DiscoverViewModel>()
    private var articleAdapter : ArticleListAdapter?= null


    /**
     * 文章id列表，用来维护本地存储防重复
     */
    private val articleIdList = mutableListOf<String>()

    companion object{

        @JvmStatic
        fun newInstance(tagId: String) : TagArticleFragment{
            val fragment = TagArticleFragment()
            val bundle = Bundle()
            bundle.putString("tagId" , tagId)
            fragment.arguments = bundle
            return fragment
        }
    }


    override fun layoutId(): Int {
        return R.layout.fragment_tag_article
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        tagId = arguments?.getString("tagId") ?: ""
        binding?.refreshArticleList?.setOnRefreshListener {
            discoverViewModel.getArticleByTag(tagId)
        }
        if(!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this)
        }
        if(NetworkUtils.isConnected()){
            discoverViewModel.getArticleByTag(tagId)
        }else{
            getDataFromCache()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getNetworkEvent(netWorkEvent: NetWorkEvent){
        if(netWorkEvent.isConnected){
            discoverViewModel.getArticleByTag(tagId)
        }else{
            getDataFromCache()
        }
    }

    /**
     * 从缓存中获取数据
     */
    fun getDataFromCache(){
        val cacheList = mutableListOf<ArticleModel>()
        DbManager.getInstance().getDatabase().articleTagDao().selectByTag(tagId).forEach { articleTag ->
            articleTag.article?.let { cacheList.add(it) }
        }
        articleAdapter?.submitList(cacheList)
    }

    override fun initView() {
        binding?.rvTagArticle?.layoutManager = LinearLayoutManager(requireContext())
        articleAdapter = ArticleListAdapter(mutableListOf())
        binding?.rvTagArticle?.adapter = articleAdapter

        articleAdapter?.setOnItemClickListener { adapter, view, position ->
            val item = adapter.getItem(position)
            val intent = Intent(requireContext() , ArticleDetailActivity::class.java)
            val params = bundleOf(
                Pair("articleId", item?.id ?: "")
            )
            intent.putExtras(params)
            startActivity(intent)
        }
    }



    override fun observeData() {
        discoverViewModel.tagArticleData.observe(this){data ->
            if (data.code == "0"){
                if(binding?.rvTagArticle?.itemDecorationCount == 0){
                    binding?.rvTagArticle?.addItemDecoration(VerticalSpaceItemDecoration(15 , data.total.toInt()))
                }
                data?.data?.let {
                    articleIdList.clear()
                    DbManager.getInstance().getDatabase().articleTagDao().deleteById(tagId)
                    val dbData = mutableListOf<ArticleTagTable>()
                    for (articleModel in it) {
                        if(!articleIdList.contains(articleModel.id)){
                            dbData.add(ArticleTagTable(tagId , article = articleModel))
                            articleIdList.add(articleModel.id)
                        }
                    }
                    DbManager.getInstance().getDatabase().articleTagDao().insertArticle(*dbData.toTypedArray())
                    articleAdapter?.submitList(it)
                }
            }
            binding?.refreshArticleList?.finishRefresh()
        }
    }

    override fun bindingClazz(): Class<out ViewBinding> {
        return FragmentTagArticleBinding::class.java
    }

    override fun onNetWorkError(msg: String) {

    }

    override fun onDestroy() {
        super.onDestroy()
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this)
        }
    }

}